const Game={
	//存放生成的敌机,子弹
	enemies:[],
	bullets:[],
	//存放战机
//	fighter:new Fighter(),
//	fighter:Fighter,

	addListener:function(){
		const that=this;
		/*点击开始*/
		on(Map.startElement,"click",function(){
			this.style.display="none";
			that.paly();
		});
		//鼠标在游戏界面上移动
		on(Map.gameElement,"mousemove",function(e){
			let x=e.pageX-this.offsetParent.offsetLeft,
				y=e.pageY-this.offsetParent.offsetTop;
			//战机移动
			Fighter.move(x,y);
		});
	},
	//组织游戏
	paly:function(){
		let count=0;
		//生成敌机
		const timer=setInterval(()=>{
			count++;
			//小型敌机
			if(count%60===0){
				this.enemies.push(EnemyFactory.createEnemy("small"));
			}
			//中型敌机
			if(count%120===0){
				this.enemies.push(EnemyFactory.createEnemy("middle"));
			}
			//大型敌机
			if(count%180===0){
				this.enemies.push(EnemyFactory.createEnemy("big"));
			}
			//每架敌机都移动
			this.enemies.forEach((curr)=>{
				curr.move();
			});
			//生成子弹
			if(count%30===0){
				const arr=[1,2,3]
				for(let i=0;i<arr.length;i++){
					//左边子弹
					if(arr[i]=1){
						const bullet=new Bullet({
							width:6,
							height:14,
							x:Fighter.x+Fighter.width/2-15,
							y:Fighter.y-15,
							img:"images/bullet.png",
							speed:-2
						})
						this.bullets.push(bullet)
					}
					//中间子弹
					if(arr[i]=2){
						const bullet=new Bullet({
							width:6,
							height:14,
							x:Fighter.x+Fighter.width/2-3,
							y:Fighter.y-15,
							img:"images/bullet.png",
							speed:-2
						})
						this.bullets.push(bullet)
					}
					//右边子弹
					if(arr[i]=3){
						const bullet=new Bullet({
							width:6,
							height:14,
							x:Fighter.x+Fighter.width/2+10,
							y:Fighter.y-15,
							img:"images/bullet.png",
							speed:-2
						})
						this.bullets.push(bullet)
					}
				}
			}
			//每颗子弹都移动
			this.bullets.forEach((curr)=>{
				curr.move();
			})
			//判断敌机、子弹、战机是否碰撞
			for(let i=this.enemies.length-1;i>=0;i--){
				const enemy=this.enemies[i];
				for(let j=this.bullets.length-1;j>=0;j--){
					const bullet=this.bullets[j];
					//调用判断方法是否碰撞
					const b=this.check(enemy,bullet);
					if(b==false){//碰撞,销毁资源
						enemy.destroy();
						bullet.destroy();
						this.bullets.splice(j,1);
						this.enemies.splice(i,1);
						break;
					}
				}
			}
			for(let i=this.enemies.length-1;i>=0;i--){
				const enemy=this.enemies[i];
				//判断是否与战机碰撞
				
				if(this.check(enemy,Fighter)===false){
					enemy.destroy();
					this.enemies.splice(i,1);
					Fighter.destroy();					
					clearInterval(timer);
					Map.endElement.style.display="block";
					break;
				}
			}
		},1000/60)
	},
	//判断是否碰撞
	//返回true是未碰撞，false是未碰撞
	check:function(role1,role2){  //role1是战机role2是敌机
		return	(role1.y>role2.y+role2.height
		||role1.y+role1.height<role2.y
		||role1.x>role2.x+role2.width
		||role1.x+role1.width<role2.x)
	},
	
	start:function(){
		this.addListener()
	}
}
//启动游戏
Game.start()


